<?php
    require('conn.cfg.php');
    
    $msg ="ack=ko&msg=undefined";
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'smarty'){
        $shipAddress1   = mysql_real_escape_string($_REQUEST['shipAddress1']);
        $shipCity       = mysql_real_escape_string($_REQUEST['shipCity']);
        $shipState      = mysql_real_escape_string($_REQUEST['shipState']);
        $shipPostalcode = mysql_real_escape_string($_REQUEST['shipPostalcode']);

        // Customize this (get ID/token values in your SmartyStreets account)
        $authId = urlencode(AUTH_ID);
        $authToken = urlencode(AUTH_TOKEN);

        $fields = array(
            'street' => $shipAddress1,
            'city' => $shipCity,
            'state' => $shipState,
            'zipCode' => $shipPostalcode,
            'candidates' => '5'
        );

        // Initialize cURL
        $ch = curl_init();

        // Configure the cURL command
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_VERBOSE, 0);
        curl_setopt($ch, CURLOPT_URL, "https://api.qualifiedaddress.com/street-address/?auth-id={$authId}&auth-token={$authToken}");
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array($fields)));

        // Output comes back as a JSON string.
        $json_output = curl_exec($ch);

        //close connection
        curl_close($ch); 

        // Show results
        $addressInfo = json_decode($json_output, TRUE);

        if(isset($addressInfo[0]['components'])){
            $street = $addressInfo[0]['components']['primary_number'].' '.$addressInfo[0]['components']['street_name'].' '.$addressInfo[0]['components']['street_suffix'];        
            $city   = $addressInfo[0]['components']['city_name'];
            $state  = $addressInfo[0]['components']['state_abbreviation'];
            $zipcode= $addressInfo[0]['components']['zipcode'];
            $msg = "ack=ok&shipaddress1=".$street."&shipcity=".$city."&shipstate=".$state."&shippostalcode=".$zipcode;
        }else{
            $msg = "ack=ko&msg=shipping address is invalid";
        }     
    }
    
    echo $msg;
?>